package com.dbflow5.database;

import com.dbflow5.StringUtils;
import com.dbflow5.config.FlowLog;
import ohos.app.Context;
import ohos.global.resource.Entry;
import ohos.global.resource.RawFileEntry;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

/**
 * Description: Implements [MigrationFileHelper] for Ohos targets.
 */
public class OhosMigrationFileHelper implements MigrationFileHelper {
    private final Context context;

    public OhosMigrationFileHelper(Context context){
        this.context = context;
    }

    @Override
    public List<String> getListFiles(String dbMigrationPath) {
        RawFileEntry rawFileEntry = context.getResourceManager().getRawFileEntry("entry/resources/rawfile/" + dbMigrationPath);
        List<String> filePathList = new ArrayList<>();
        try {
            Entry[] entries = rawFileEntry.getEntries();
            for (Entry entry : entries) {
                if(entry.getType() == Entry.Type.FILE) {
                    filePathList.add(entry.getPath());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return filePathList;
    }

    @Override
    public void executeMigration(String fileName, Function<String, Void> dbFunction) {
        try {
            InputStream input = context.getResourceManager().getRawFileEntry("entry/resources/rawfile/" + fileName).openRawFile();

            // ends line with SQL
            String querySuffix = ";";

            // standard java comments
            String queryCommentPrefix = "--";
            StringBuffer query = new StringBuffer();

            InputStreamReader reader = new InputStreamReader(input, StandardCharsets.UTF_8);
            BufferedReader bufferedReader = new BufferedReader(reader, 8*1024);
            String fileLine;
            while((fileLine = bufferedReader.readLine()) != null){
                String line = fileLine.trim();
                boolean isEndOfQuery = line.endsWith(querySuffix);
                if (line.startsWith(queryCommentPrefix)) {
                    return;
                }
                if (isEndOfQuery) {
                    line = line.substring(0, line.length() - querySuffix.length());
                }
                query.append(" ").append(line);
                if (isEndOfQuery) {
                    dbFunction.apply(query.toString());
                    query = new StringBuffer();
                }
            }

            String queryString = query.toString();
            if (StringUtils.isNotNullOrEmpty(queryString.trim())) {
                dbFunction.apply(queryString);
            }
        } catch (IOException e) {
            FlowLog.log(FlowLog.Level.E, "Failed to execute "+fileName+". App might be in an inconsistent state!", e);
        }
    }
}